package com.riteny.util.exception.datasource;

import com.riteny.util.exception.properties.InternationalizationProfile;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ResourceUtils;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Riteny
 * <p>
 * Update by Riteny 2021/12/1
 * 默認的數據源，通過讀取項目路徑下il8n文件夾内所有以.exception.properties為後綴文件的内容
 * 填充對應的異常消息鍵值對到{@link InternationalizationProfile} 内
 * 并以{lang}.exception.properties 中的lang作爲該語言的標識
 * 文件内容以 errorCode=errorMsg 的方式存儲
 * <p>
 * 2021/9/10  15:27
 */
public class PropertiesFileProfileSource implements ProfileSource {

    @Override
    public void initErrorCodeProfile() {

        Map<String, Map<String, String>> profile = new HashMap<>();

        try {
            //step1 獲取文件夾内所有國際化文件配置，以文件名作爲語言的縮寫，例如tc,sc,en,jp等
            Resource[] resources = new PathMatchingResourcePatternResolver().
                    getResources(ResourceUtils.CLASSPATH_URL_PREFIX + "i18n/*.exception.properties");

            for (Resource resource : resources) {
                Map<String, String> errorCodeMap = new HashMap<>();

                //step2 讀取配置文件内的所有異常碼和對應的異常消息内容
                Properties propertiesUtil = new Properties();
                propertiesUtil.load(resource.getInputStream());

                Enumeration it = propertiesUtil.keys();
                while (it.hasMoreElements()) {

                    String key = (String) it.nextElement();
                    String value = propertiesUtil.getProperty(key);

                    errorCodeMap.put(key, value);
                }

                //step3 設置國際化對象的語言縮寫
                String langType = resource.getFilename().replace(".exception.properties", "");
                profile.put(langType, errorCodeMap);
            }

            InternationalizationProfile.setProfiles(profile);

        } catch (IOException e) {
            throw new RuntimeException("Internationalization Profile File init fail . " + e.getMessage());
        }
    }
}
